<template>
  <view>
    <view class="goods-list">
      <view v-for="(goods,i) in goodsList" :key="i" @click="gotoDetail(goods)">
        <my-goods :goods="goods"></my-goods>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        //请求参数对象
        queryObj: {
          query: '',
          cid: '',
          pagenum: 1,
          pagesize: 10 //根据需要自定义
        },
        goodsList: [],
        total: 0, //分页需要
        isLoading: false, //截流阀
        
        //默认的图片地址（没有图片的商品使用）
        defaultPic: 'https://img3.doubanio.com/f/movie/8dd0c794499fe925ae2ae89ee30cd225750457b4/pics/movie/celebrity-default-medium.png'
      };
    },
    
    onLoad(options){
      // console.log(options)
      this.queryObj.query = options.query || ''
      this.queryObj.cid = options.cid || ''
      // console.log(this.queryObj)
      
      this.getGoodsList()
    },
    
    methods:{
      //获取商品列表数据
      async getGoodsList(cb){ //2步cb: 如果有传值，就接收
        //请求之前，开启截流阀
        this.isLoading = true
        const {data: res} =  await uni.$http.get('/api/public/v1/goods/search',this.queryObj)
        //请求完毕，关闭截流阀
        this.isLoading = false
        cb && cb() //3步：短路运算，如果存在就调用
        
        if(res.meta.status !== 200) return uni.$showMsg()
        
        //否则，给变量赋值
        // this.goodsList = res.message.goods
        this.goodsList = [...this.goodsList, ...res.message.goods] //新旧数据拼接
        this.total = res.message.total
      },
      
      //跳转到商品详情页
      gotoDetail(goods){
        uni.navigateTo({
          url: '/subpkg/goods_list/goods_list?goods_id='+goods.goods_id
        })
      }
    },
    
    //上拉触底，加载更多数据
    onReachBottom(){
      //当没有更多数据，返回，并提示信息
      if(this.queryObj.pagenum*this.queryObj.pagesize >= this.total) return uni.$showMsg('数据加载完毕!')
      //先判断，如果截流阀正在开启，则返回
      if(this.isLoading) return
      
      //否则，进行加载数据
      this.queryObj.pagenum++  //让页面值自增
      this.getGoodsList() //同时调用获取商品列表方法
    },
    
    onPullDownRefresh() {
      //重置关键数据
      this.queryObj.pagenum = 1
      this.total = 0
      this.isLoading = false
      this.goodsList = []
      //重新发起数据请求 4步：关闭下拉刷新效果
      this.getGoodsList(()=>uni.stopPullDownRefresh())
    }
  }
</script>

<style lang="scss">
  .goods-item{
    display: flex;
    padding: 10px 5px;
    border-bottom: 1px solid #dddddd;
    
    .goods-item-left{
      margin-right: 6px;
      
      .goods-pic{
        width: 100px;
        height: 100px;
        border-radius: 6px;
        display: block;//防止图片下面有空白间隙
      }
    }
    .goods-item-right{
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      
      .goods-name{
        font-size: 13px;
      }
      .goods-info-box{
        .goods-price{
          color: #c00000;
          font-size: 16px;
        }
      }
    }
  }
</style>
